package cn.wolfcode.luowowo.website.controller;

import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.common.util.RedisKey;
import cn.wolfcode.luowowo.member.service.IUserInfoService;
import cn.wolfcode.luowowo.website.annotation.RequireLogin;
import cn.wolfcode.luowowo.website.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class LoginController {

    @Reference
    private IUserInfoService userInfoService;

    @RequireLogin
    @RequestMapping("/hello")
    @ResponseBody
    public Object hello(Long id){
        return userInfoService.get(id);
    }

    //手机号注册的控制器
    @RequestMapping("/checkPhone")
    @ResponseBody
    public Object checkPhone(String phone){
        //若为true则代表已经被注册,取反返回前端
        return !userInfoService.checkPhone(phone);
    }

    //发送验证码的控制器
    @RequestMapping("/sendVerifyCode")
    @ResponseBody
    public Object sendVerifyCode(String phone){
        userInfoService.sendVerifyCode(phone);
        return AjaxResult.SUCCESS;
    }

    //发送验证码的控制器
    @RequestMapping("/userRegist")
    @ResponseBody
    public Object userRegist(String phone, String nickname, String password,
                             String rpassword, String verifyCode){
        userInfoService.userRegist(phone, nickname, password, rpassword, verifyCode);
        return AjaxResult.SUCCESS;
    }

    //发送验证码的控制器
    @RequestMapping("/userLogin")
    @ResponseBody
    public Object userLogin(String username, String password,
                            HttpServletRequest request, HttpServletResponse response){
        String token = userInfoService.userLogin(username, password);
        CookieUtil.saveCookie("token", token,
                RedisKey.USER_LOGIN_TOKEN.getTime().intValue(), response);
//        //5. 得到token变量, 创建cookie对象, 将token变量名和token的值(UUID)设置在cookie中
//        //并设置cookie的有效时间为30分钟, 以及共享路径(不要忘记)
//        //再通过response对象将cookie传到浏览器中缓存
//        Cookie cookie = new Cookie("token", token);
//        //设置有效时间
//        cookie.setMaxAge(RedisKey.USER_LOGIN_TOKEN.getTime().intValue());
//        //设置共享路径
//        cookie.setPath("/");

        return AjaxResult.SUCCESS;
    }

}
